<?php


namespace app\miniProgram\severs;


use think\facade\Config;
use think\facade\Db;

class Admin extends Base
{
    public static function login($param)
    {
        $comInfo=Db::name('company')->where('status',1)->where('id',$param['cId'])->find();
        if (!$comInfo){
            return self::jump(0,'信息有误');
        }
        $comConnect=[
            'type'               =>  'mysql',
            'hostname'           =>  $comInfo['ip'],
            'database'           =>  $comInfo['databaseName'],
            'username'           =>  $comInfo['username'],
            'password'           =>  $comInfo['password'],
            'hostport'           =>  '3306',
            // 数据库表前缀
            'prefix'             =>  'fy_',
            // 数据库连接参数
            'params'          => [],
            // 数据库编码默认采用utf8mb4
            'charset'         => 'utf8mb4',
            // 数据库调试模式
            'debug'           => false,
            // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
            'deploy'          => 0,
            // 数据库读写是否分离 主从式有效
            'rw_separate'     => false,
            // 读写分离后 主服务器数量
            'master_num'      => 1,
            // 指定从服务器序号
            'slave_no'        => '',
            // 是否严格检查字段是否存在
            'fields_strict'   => true,
            // 是否需要断线重连
            'break_reconnect' => false,
            // 监听SQL
            'trigger_sql'     => true,
            // 开启字段缓存
            'fields_cache'    => false,
        ];
        $config=Config::get('database');
        $config['connections']['company']=$comConnect;
        Config::set($config,'database');

        $admin = Db::connect('company')->name('Admin')->where(['mobile' => $param['phone']])->find();
        if (empty($admin)) {
            return self::jump(0, '用户不存在');
        }
//        $param['pwd'] = set_password($param['password'], $admin['salt']);
//        if ($admin['pwd'] !== $param['pwd']) {
//            return self::jump(0, '用户或密码错误');
//        }
        if ($admin['status'] != 1) {
            return self::jump(0, '账号异常,请与管理者联系');
        }
        try {
            $data = [
                'is_lock' => 0,
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
                'login_num' => $admin['login_num'] + 1,
            ];
            Db::connect('company')->name('admin')->where(['id' => $admin['id']])->update($data);
            $logdata = [
                'uid' => $admin['id'],
                'type' => 'login',
                'action' => '登录',
                'subject' => '小程序',
                'param_id'=>$admin['id'],
                'param'=>'[]',
                'ip' => request()->ip(),
                'create_time' => time()
            ];
            $admin['cId']=$comInfo['id'];
            Db::connect('company')->name('AdminLog')->strict(false)->field(true)->insert($logdata);
        }catch (\Exception $e){
            return self::jump(0,$e->getMessage());
        }

        return self::createLoginParam($admin,'登录成功');
}

    public static function createLoginParam($userInfo,$message = '登陆成功'){
        return self::jump(1, $message, [
            "authorization" =>'Basic '. base64_encode($userInfo['username'] . ":" . $userInfo['salt'] . ":".$userInfo['cId'] . ":" .time()),
            'name'=>$userInfo['name'],
            'mobile'=>$userInfo['mobile'],
            'id'=>$userInfo['id'],
            'auth'=>self::getAuth($userInfo['id'])
        ]);

    }
    public static function getAuth($uid)
    {
        $position_id = Db::connect('company')->name('Admin')->where('id', $uid)->value('position_id');
        $groups = Db::connect('company')->name('PositionGroup')
            ->alias('a')
            ->join("AdminGroup g", "a.group_id=g.id", 'LEFT')
            ->where([['a.pid', '=', $position_id], ['g.status', '=', 1]])
            ->select()->toArray();
        //保存用户所属用户组设置的所有权限规则id
        $ids = [];
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        //读取所有权限规则
//        $rules_all = Db::name('AdminRule')->field('src')->select()->toArray();
        //读取用户组所有权限规则
        $rules = Db::connect('company')->name('AdminRule')->where('id', 'in', $ids)->field('src')->select()->toArray();
        //循环规则，判断结果。
//        $auth_list_all = [];
        $auth_list = [];
//        foreach ($rules_all as $rule_all) {
//            $auth_list_all[] = strtolower($rule_all['src']);
//        }
        foreach ($rules as $rule) {
            $str=strtolower($rule['src']);
            $strs=$str?explode('/',$str):[];
            $src='';
            if (!empty($strs)){
                unset($strs[0]);

                $auth_list[] = implode('/',$strs);
            }
        }
        return $auth_list;
    }
}